package com.sxkf.template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxkf.template.entity.Product;
import com.sxkf.template.mapper.ProductMapper;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxkf.template.entity.Category;
import com.sxkf.template.mapper.CategoryMapper;
import com.sxkf.template.service.CategoryService;

import javax.annotation.Resource;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService{
    @Resource
    private ProductMapper productMapper;
    @Override
    public List<Category> listCategoryByStoreId(String storeId) {
        // 查询店铺中商品的信息
        List<Product> productList = productMapper.selectList(new LambdaQueryWrapper<Product>()
                .select(Product::getName,Product::getImageUrl,Product::getCategoryId)
                .eq(Product::getStoreId, storeId));

        List<Category> categories = new ArrayList<>();
        if (!productList.isEmpty()){
            //查询出所有商品的分类
            Set<String> categoryIds = productList.stream().map(Product::getCategoryId).collect(Collectors.toSet());
            categories = listByIds(categoryIds);

            Map<String, List<Product>> productMap = productList.stream().collect(Collectors.groupingBy(Product::getCategoryId));

            //给分类补充商品
            categories.forEach(category -> category.setProducts(productMap.get(category.getId())));
        }
        return categories;
    }

    @Override
    public IPage<Category> rank(Integer pageNo, Integer pageSize, String categoryId) {
        Page<Category> page = page(new Page<>(pageNo, pageSize));
        page.getRecords().forEach(item->{
            List<Product> products = productMapper.selectList(new LambdaQueryWrapper<Product>().eq(Product::getCategoryId, item.getId()).orderByDesc(Product::getSaleCount).last("limit 3"));
            item.setProducts(products);
        });
        return page;
    }
}
